#_*_coding:utf-8_*_
__author__ = 'jieli'
from CrazyEye import settings
import os, tempfile, zipfile
from django.http import HttpResponse
#from django.core.servers.basehttp import FileWrapper
from wsgiref.util import FileWrapper #from django.core.servers.basehttp import FileWrapper
from web import models
import django
from django.db.models import Count,Sum
from backend import utils
import random,json,datetime,time
# from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
import paramiko
import xlrd
import hashlib
from django.shortcuts import redirect

def handle_upload_file(request,random_str,response_dic):
    upload_dir = '%s/task_data/tmp/%s' %(settings.FileUploadDir,random_str)
    if not os.path.isdir(upload_dir):
        os.makedirs(upload_dir,exist_ok=True)

    for k,file_obj in request.FILES.items():
        if len(os.listdir(upload_dir)) <= settings.MaxUploadFiles:
            with open('%s/%s' %(upload_dir,file_obj.name),'wb') as destination :
                for chunk in file_obj.chunks():
                    destination.write(chunk)
        else:
            response_dic['error'] = "can only upload no more than %s files." % (settings.MaxUploadFiles)


def send_file(request):
    """
    Send a file through Django without loading the whole file into
    memory at once. The FileWrapper will turn the file object into an
    iterator for chunks of 8KB.
    """
    filename = __file__ # Select your file here.
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='text/plain')
    response['Content-Length'] = os.path.getsize(filename)
    return response


def ssh_cmd(ip,port,cmd):
    s = paramiko.SSHClient()
    # s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname=ip, username='root', port=port, key_filename=settings.RSA_PRIVATE_KEY_FILE)
    stdin, stdout, stderr = s.exec_command(cmd)
    result = stdout.readlines()
    s.close()
    return result


def sftp_down(ip,port,path):

    current_time=int(time.time())
    dir='/tmp/%s' % str(current_time)
    if not os.path.isdir(dir):
        os.makedirs(dir,exist_ok=True)
    file=path.split('/')[-1]
    local_path=os.path.join(dir,file)
    try:
        key = paramiko.RSAKey.from_private_key_file(settings.RSA_PRIVATE_KEY_FILE)
        t = paramiko.Transport((ip, port))
        t.connect(username='root', pkey=key)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.get(path, local_path)
        t.close()
    except Exception as e:
        print(e)
    return local_path

def hosts_insert(file):
    message=''
    try:
        wb=xlrd.open_workbook(file,encoding_override='gb2312')
    except Exception as e:
        print(e)
    sh = wb.sheet_by_index(0)
    count=sh.nrows
    for i in range(1,count):
        data=sh.row_values(rowx=i)
        print(data)
        hostname,ip,idc,account,port=data
        try:
            idcobj=models.IDC.objects.get(name=idc)
        except Exception as e:
            idcobj=models.IDC(name=idc)
            idcobj.save()
        try:
            accountobj=models.Account.objects.get(username=account)
        except Exception as e:
            accountobj=models.Account(username=account)
            accountobj.save()

        hostobj=models.Hosts.objects.filter(ip_addr=ip)
        if hostobj:
            message=message+'The Host %s is exists!' % (ip)
            continue
        else:
            hostobj=models.Hosts(hostname=hostname,ip_addr=ip,idc=idcobj,account=accountobj,port=int(port))
            hostobj.save()
    print(message)
    return message


def cdn_insert(file):
    message=''
    try:
        wb=xlrd.open_workbook(file,encoding_override='gb2312')
    except Exception as e:
        print(e)
    sh = wb.sheet_by_index(0)
    count=sh.nrows
    for i in range(1,count):
        data=sh.row_values(rowx=i)
        print(data)
        domain,cdnuser=data
        try:
            cdnuserobj=models.CDNUser.objects.get(name=cdnuser)
        except Exception as e:
            cdnuserobj=models.CDNUser(name=cdnuser)
            cdnuserobj.save()

        domainobj=models.CDNDomain.objects.filter(name=domain)
        if domainobj:
            message=message+'The domain %s is exists!' % (domain)
            continue
        else:
            domainobj=models.CDNDomain(name=domain,cdn_user=cdnuserobj)
            domainobj.save()
    print(message)
    return message

def download_switch(id,new_download):
    obj=models.DownloadUrl.objects.get(id=id)
    old_download=obj.download_url
    ip="183.136.233.105"
    message={'result':'','status':''}
    try:
        cmd0="/data0/scripts/sh/switch_download.sh bd_modified %s %s;echo $?" % (old_download,new_download)
        result=ssh_cmd(ip,22,cmd0)

        if (result[0].strip('\n') == '0'):
            message['status'] = '0'
        else:
            message['status'] = '1'
            message['result'] = '地址更新失败'
        obj.download_url=new_download
        obj.save()
    except Exception as e:
        print(e)
    return message


def ed2k_switch(id_name,new_download,action):
    ip="183.136.233.105"
    base_dir="/data0/web/wwwroot"
    thunder_url="thunder://\\\".base64_encode('AA'.\\$urlxl.'ZZ').\\\""
    message={'result':'','status':''}
    print(action)
    try:
        if action=='xunlei':
            cmd1 = "/data0/scripts/sh/switch_download.sh %s %s;echo $?" % (action, id_name)
        elif action=='ed2k':
            cmd1 = "/data0/scripts/sh/switch_download.sh %s %s '%s';echo $?" % (action, id_name, new_download.strip())
            if new_download=='':
                message['result']='新地址不能为空'
                raise Exception('new_download不能为空')
        elif action=='ed2k_modified':
            cmd1 = "/data0/scripts/sh/switch_download.sh %s %s '%s';echo $?" % (action, id_name, new_download.strip())
            if new_download=='':
                message['result']='新地址不能为空'
                raise Exception('new_download不能为空')
        else:
            message['result'] = '请选择动作'
            raise Exception('请选择动作')
        result=ssh_cmd(ip,22,cmd1)
        if(result[0].strip('\n')=='0'):
            message['status']='0'
        else:
            message['status']='1'
            message['result']='地址切换失败'
    except Exception as e:
        print(e)
        message['status']='1'
        message['result']='请联系运维！'
        return message
    return message

def nav_add(ip,domain,t,site,navigate,statics):
    text=models.NavType.objects.get(id=site).html_text
    base_dir="/home/wwwroot"
    domain1=domain
    domain=domain.split('.')
    dir1=domain[0]
    dir2=".".join(domain[1:])
    dir="%s/%s/%s" %(base_dir,dir2,dir1)
    nginx_conf_dir="/usr/local/nginx/conf/vhost"
    nginx_conf="%s.conf" % (dir2)
    nginx_conf_text='''
server {
      listen       80;
      server_name %s;
      location / {
          root   %s;
          index index.html;
      }
      location = /favicon.ico {
            log_not_found off;
            access_log off;
       }
}
''' % (domain1,dir)
    cmd0="[ -d %s ] && echo 0 || echo 1" % (dir)
    cmd1="mkdir -p %s;cd %s;echo '%s'>index.html;echo $?" % (dir,dir,text)
    print(type(t))
    if '&' in statics:
        statics=statics.replace('&','\&')
    if '&' in navigate:
        navigate=navigate.replace('&','\&')
    if t=='1':
        if navigate!='' and statics!='':
            cmd2="cd %s;sed -i 's#url=.*\">#url=%s\">#' index.html;sed -i 's#src=\".*\"#src=\"%s\"#' index.html;echo $?" % (dir,navigate,statics)
        elif navigate!='' and statics=='':
            cmd2 = "cd %s;sed -i 's#url=.*\">#url=%s\">#' index.html;echo $?" % (dir, navigate)
        elif navigate=='' and statics!='':
            cmd2 = "cd %s;sed -i 's#src=\".*\"#src=\"%s\"#' index.html;echo $?" % (dir, statics)
        else:
            cmd2 = "echo 'do nothing!'"
    elif t=='2':
        if navigate!='':
            cmd2="cd %s;sed -i 's#href=\".*\"#href=\"%s\"#' index.html;echo $?" % (dir,navigate)
        else:
            cmd2="echo 'do nothing!'"

    cmd3="cd %s;echo '%s'>>%s;nginx -t;echo $?" % (nginx_conf_dir,nginx_conf_text,nginx_conf)
    cmd4="nginx -s reload"
    try:
        result0=ssh_cmd(ip,22,cmd0)
        if result0[0].strip('\n') == '0':
            result='导航域名已经存在！'
        else:
            print(ssh_cmd(ip,22,cmd1))
            print(ssh_cmd(ip,22,cmd2))
            result3 = ssh_cmd(ip, 22, cmd3)
            if result3[0].strip('\n') == '0':
                ssh_cmd(ip,22,cmd4)
                result='导航域名添加成功！'
            else:
                result='nginx配置文件异常！'
    except Exception as e:
        result=e
    return result



def nav_mod(ip,domain,t,navigate,statics):
    base_dir="/home/wwwroot"
    domain=domain.split('.')
    dir1=domain[0]
    dir2=".".join(domain[1:])
    dir = "%s/%s/%s" % (base_dir, dir2, dir1)
    cmd1="[ -d %s ] && echo 0 || echo 1" % (dir)
    if '&' in statics:
        statics=statics.replace('&','\&')
    if '&' in navigate:
        navigate=navigate.replace('&','\&')
    if t=='1':
        if navigate!='' and statics!='':
            cmd2="cd %s;sed -i 's#url=.*\">#url=%s\">#' index.html;sed -i 's#src=\".*\"#src=\"%s\"#' index.html;echo $?" % (dir,navigate,statics)
        elif navigate!='' and statics=='':
            cmd2 = "cd %s;sed -i 's#url=.*\">#url=%s\">#' index.html;echo $?" % (dir, navigate)
        elif navigate=='' and statics!='':
            cmd2 = "cd %s;sed -i 's#src=\".*\"#src=\"%s\"#' index.html;echo $?" % (dir, statics)
        else:
            cmd2 = "echo 'do nothing!'"
    elif t=='2':
        if navigate!='':
            cmd2="cd %s;sed -i 's#href=\".*\"#href=\"%s\"#' index.html;echo $?" % (dir,navigate)
        else:
            cmd2="echo 'do nothing!'"
    try:
        result1=ssh_cmd(ip,22,cmd1)
        if result1[0].strip('\n') == '1':
            result = '导航不存在！'
        else:
            result2=ssh_cmd(ip,22,cmd2)
            if result2[0].strip('\n') == '0':
                result = '导航修改成功！'
            else:
                result = '导航修改失败！'
    except Exception as e:
        result = e
    return result


def nav_del(ip,domain):
    base_dir='/home/wwwroot'
    domain1=domain
    domain=domain.split('.')
    dir1=domain[0]
    dir2=".".join(domain[1:])
    dir="%s/%s/%s" % (base_dir,dir2,dir1)
    nginx_conf_dir="/usr/local/nginx/conf/vhost"
    nginx_conf="%s.conf" % (dir2)
    cmd1="[ -d %s ] && echo 0 || echo 1" % (dir)
    cmd2="rm -rf %s;cd %s;sed -i '/%s/,+9d;:go;1,3!{P;$!N;D};N;bgo' %s;echo $?" % (dir,nginx_conf_dir,domain1,nginx_conf)
    cmd3="nginx -t;echo $?"
    cmd4="nginx -s reload"
    try:
        result1=ssh_cmd(ip,22,cmd1)
        if result1[0].strip('\n')=='1':
            result='导航不存在！'
        else:
            print(ssh_cmd(ip,22,cmd2))
            result3=ssh_cmd(ip,22,cmd3)
            if result3[0].strip('\n')=='0':
                ssh_cmd(ip,22,cmd4)
                result='导航已删除！'
            else:
                result='nginx配置文件有异常，请检查！'
    except Exception as e:
        result=e
    return result


def mysql_select_port(ip,ssh_port):
    try:
        cmd="netstat -tnlp|grep mysql|awk '{print $4}'|awk -F: '{print $2}'"
        port_list=ssh_cmd(ip,ssh_port,cmd)
        port_list=[port.strip('\n') for port in port_list]
        return port_list
    except Exception as e:
        return []

def get_mysql_user(ip,ssh_port,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'select user,host from mysql.user order by user;' -s" % mysql_port
    user_list=ssh_cmd(ip,ssh_port,cmd)
    user_list=[ x.strip('\n').split('\t') for x in user_list]
    if len(user_list)==0:
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'select user,host from mysql.user order by user;' -s" % mysql_port
        user_list = ssh_cmd(ip, ssh_port, cmd)
        user_list = [x.strip('\n').split('\t') for x in user_list]
    return user_list

def mod_mysql_user(ip,ssh_port,user,host,passwd,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'set password for \"%s\"@\"%s\" = PASSWORD(\"%s\");' -s;echo $?" % (mysql_port,user,host,passwd)
    result=ssh_cmd(ip,ssh_port,cmd)
    if result[0].strip('\n')!=0:
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'set password for \"%s\"@\"%s\" = PASSWORD(\"%s\");' -s;echo $?" % (mysql_port,user, host, passwd)
        result=ssh_cmd(ip,ssh_port,cmd)
    return result

def add_mysql_user(ip,ssh_port,user,host,passwd,dbname,is_first,db_type,mysql_port):
    cmd1="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'grant alter,create,delete,index,insert,select,update on %s.* to \"%s\"@\"%s\" identified by \"%s\";' -s;echo $?" %(mysql_port,dbname,user,host,passwd)
    cmd2="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'grant alter,create,delete,index,insert,select,update on %s.* to \"%s\"@\"%s\";' -s;echo $?" %(mysql_port,dbname,user,host)
    cmd3="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'grant alter,create,delete,index,insert,select,update,drop on %s.* to \"%s\"@\"%s\" identified by \"%s\";' -s;echo $?" %(mysql_port,dbname,user,host,passwd)
    cmd4="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'grant alter,create,delete,index,insert,select,update,drop on %s.* to \"%s\"@\"%s\";' -s;echo $?" %(mysql_port,dbname,user,host)
    if is_first and db_type=='prod':
        result = ssh_cmd(ip, ssh_port, cmd1)
        if result[0].strip('\n')!='0':
            cmd1 = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'grant alter,create,delete,index,insert,select,update on %s.* to \"%s\"@\"%s\" identified by \"%s\";' -s;echo $?" % (mysql_port,dbname, user, host, passwd)
            result = ssh_cmd(ip, ssh_port, cmd1)
    elif not is_first and db_type=='prod':
        result=ssh_cmd(ip,ssh_port,cmd2)
        if result[0].strip('\n')!='0':
            cmd2 = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'grant alter,create,delete,index,insert,select,update on %s.* to \"%s\"@\"%s\";' -s;echo $?" % (mysql_port,dbname, user, host)
            result = ssh_cmd(ip, ssh_port, cmd2)
    elif is_first and db_type=='dev':
        result = ssh_cmd(ip, ssh_port, cmd3)
        if result[0].strip('\n')!='0':
            cmd3 = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'grant alter,create,delete,index,insert,select,update,drop on %s.* to \"%s\"@\"%s\" identified by \"%s\";' -s;echo $?" % (mysql_port,dbname, user, host, passwd)
            result = ssh_cmd(ip, ssh_port, cmd3)
    else:
        result=ssh_cmd(ip,ssh_port,cmd4)
        if result[0].strip('\n')!='0':
            cmd4 = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'grant alter,create,delete,index,insert,select,update,drop on %s.* to \"%s\"@\"%s\";' -s;echo $?" % (mysql_port,dbname, user, host)
            result = ssh_cmd(ip, ssh_port, cmd4)
    return result

def del_mysql_user(ip,ssh_port,user,host,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'drop user \"%s\"@\"%s\"' -s;echo $?" % (mysql_port,user,host)
    result=ssh_cmd(ip,ssh_port,cmd)

    if result[0].strip('\n')!='0':
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'drop user \"%s\"@\"%s\"' -s;echo $?" % (mysql_port,user, host)
        result = ssh_cmd(ip, ssh_port, cmd)
    return result

def mysql_user_priv(ip,ssh_port,user,host,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'select user,host,db from mysql.db where user=\"%s\" and host=\"%s\" order by user;' -s" % (mysql_port,user,host)
    user_list=ssh_cmd(ip,ssh_port,cmd)
    user_list=[ x.strip('\n').split('\t') for x in user_list]
    if len(user_list)==0:
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'select user,host,db from mysql.db where user=\"%s\" and host=\"%s\" order by user;' -s" % (mysql_port,user,host)
        user_list = ssh_cmd(ip, ssh_port, cmd)
        user_list = [x.strip('\n').split('\t') for x in user_list]
    return user_list

def mysql_del_priv(ip,ssh_port,user,host,dbname,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'revoke all privileges on %s.* from \"%s\"@\"%s\";' -s;echo $?" % (mysql_port,dbname,user,host)
    result=ssh_cmd(ip,ssh_port,cmd)
    if result[0].strip("\n")!='0':
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'revoke all privileges on %s.* from \"%s\"@\"%s\";' -s;echo $?" % (mysql_port,dbname,user,host)
        result = ssh_cmd(ip, ssh_port, cmd)
    return result


def add_mysql_database(ip,ssh_port,mysql_port,database):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'create database %s;' -s;echo $?" % (mysql_port,database)
    result=ssh_cmd(ip,ssh_port,cmd)
    if result[0].strip("\n")!='0':
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'create database %s;' -s;echo $?" % (mysql_port,database)
        result = ssh_cmd(ip, ssh_port, cmd)
    return result


def select_mysql_database(ip,ssh_port,mysql_port):
    cmd="source ~/.bash_profile;mysql -h127.0.0.1 -P %s -e 'show databases;' -s" % (mysql_port)
    db_list=ssh_cmd(ip,ssh_port,cmd)
    db_list = [x.strip('\n').split('\t') for x in db_list]
    if len(db_list)==0:
        cmd = "source ~/.bash_profile;mysql -S /data0/mysql/%s/mysql.sock -e 'show databases' -s" % (mysql_port)
        db_list = ssh_cmd(ip, ssh_port, cmd)
        db_list = [x.strip('\n').split('\t') for x in db_list]
    return db_list


def md5sum(text):
    m=hashlib.md5()
    m.update(text)
    psw=m.hexdigest()
    return psw




def send_zipfile(request,task_id,file_path):
    """
    Create a ZIP file on disk and transmit it in chunks of 8KB,
    without loading the whole file into memory. A similar approach can
    be used for large dynamic PDF files.
    """
    zip_file_name = 'task_id_%s_files' % task_id
    archive = zipfile.ZipFile(zip_file_name , 'w', zipfile.ZIP_DEFLATED)
    file_list = os.listdir(file_path)
    for filename in file_list:
        archive.write('%s/%s' %(file_path,filename),arcname=filename)
    archive.close()
    wrapper = FileWrapper(open(zip_file_name,'rb'))
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=%s.zip' % zip_file_name
    response['Content-Length'] = os.path.getsize(zip_file_name)
    #temp.seek(0)
    return response

class Token(object):
    def __init__(self,request):
        self.request = request
        self.token_type = request.POST.get('token_type')
        self.token = {'token':None}
    def generate(self):
        func = getattr(self,self.token_type)
        return func()
    def host_token(self):
        bind_host_id = self.request.POST.get('bind_host_id')
        host_obj = models.BindHosts.objects.get(id=int(bind_host_id))
        latest_token_obj = models.Token.objects.filter(host_id = int(bind_host_id),user_id=self.request.user.id).last()
        token_gen_flag = False

        if latest_token_obj:

            token_gen_time_stamp = time.mktime(latest_token_obj.date.timetuple())
            current_time = time.mktime(django.utils.timezone.now().timetuple() )
            if current_time - token_gen_time_stamp >latest_token_obj.expire:#token expired
                token_gen_flag = True
        else:
            token_gen_flag = True

        if token_gen_flag:
            token = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba1234567890',6))
            models.Token.objects.create(
                user = self.request.user,
                host = host_obj,
                token = token
            )
        else:
            token = latest_token_obj.token
        self.token['token'] = token
        return  json.dumps(self.token)

def get_all_logged_in_users():
    # Query all non-expired sessions
    # use timezone.now() instead of datetime.now() in latest versions of Django
    sessions = Session.objects.filter(expire_date__gte=django.utils.timezone.now())
    uid_list = []

    # Build a list of user ids from that query
    for session in sessions:
        data = session.get_decoded()
        uid_list.append(data.get('_auth_user_id', None))

    # Query all logged in users based on id list
    return models.UserProfile.objects.filter(id__in=uid_list)

class Dashboard(object):
    def __init__(self,request):
        self.request = request

    def get(self):
        data_type = self.request.GET.get("data_type")
        assert  data_type is not None
        func = getattr(self,data_type)
        return func()
    def get_online_users(self):
        return  get_all_logged_in_users().values('name','department__name','last_login','id')

    def get_online_hosts(self):
        return   models.Session.objects.filter(closed=0).values('bind_host__host__hostname',
                                                                 'user__name',
                                                                 'bind_host__host__ip_addr',
                                                                 'bind_host__host__id',
                                                                 'bind_host__host_user__username',
                                                                 'tag',
                                                                 'cmd_count',
                                                                'stay_time',
                                                                 'id','date')
def dashboard_summary(request):
    data_dic = {
        'user_login_statistics' :[],
        'recent_active_users':[],
        'recent_active_users_cmd_count':[],
        'summary':{}
    }
    days_before_30 = django.utils.timezone.now() +django.utils.timezone.timedelta(days=-30)
    #data_dic['user_login_statistics'] = list(models.AuditLog.objects.filter(action_type=1).extra({"login_date":"date(date)"}).values_list('login_date').annotate(count=Count('pk')))
    data_dic['user_login_statistics'] = list(models.Session.objects.filter(date__gt=days_before_30).extra({'login_date':'date(date)'}).values_list('login_date').annotate(count=Count('pk')))
    days_before_7 = django.utils.timezone.now() +django.utils.timezone.timedelta(days=-7)
    #recent_active_users= models.Session.objects.all()[0:10].values('user','user__name','cmd_count').annotate(Count('user'))
    recent_active_users= models.Session.objects.all()[0:10].values("user",'user__name').annotate(Sum('cmd_count'),Count('id'))
    recent_active_users_cmd_count= models.AuditLog.objects.filter(date__gt = days_before_7,action_type=0).values('user','user__name').annotate(Count('cmd'))
    data_dic['recent_active_users'] = list(recent_active_users)
    data_dic['recent_active_users_cmd_count'] = list(recent_active_users_cmd_count)
    data_dic['summary']['total_servers'] = models.Hosts.objects.count()
    data_dic['summary']['total_users'] = models.UserProfile.objects.count()
    data_dic['summary']['current_logging_users'] = get_all_logged_in_users().count()

    #current_connection servers
    current_connected_hosts = models.Session.objects.filter(closed=0).count()

    #current_connected_hosts = login_times - logout_times
    data_dic['summary']['current_connected_hosts'] = current_connected_hosts


    return  data_dic


def recent_accssed_hosts(request):
    days_before_14 = django.utils.timezone.now() +django.utils.timezone.timedelta(days=-14)
    recent_logins = models.AuditLog.objects.filter(date__gt = days_before_14,user_id=request.user.id,action_type=1).order_by('date')
    unique_bindhost_ids = set([i[0] for i in recent_logins.values_list('host_id')])
    recent_login_hosts = []
    for h_id in unique_bindhost_ids:
        recent_login_hosts.append(recent_logins.filter(host_id=h_id).latest('date'))

    return  set(recent_login_hosts)



def login_required(func,login_url=None):
    def wrapper(request,*args,**kwargs):
        if request.session.get('session_id',None):
            return func(request,*args,**kwargs)
        else:
            if login_url:
                return redirect(login_url)
            else:
                return redirect(settings.LOGIN_URL)

